document.addEventListener('DOMContentLoaded', function() {
    // 初始化页面
    loadOrderStats();
    loadOrders();

    // 绑定搜索按钮事件
    document.getElementById('searchBtn').addEventListener('click', function() {
        loadOrders();
    });

    // 绑定筛选条件变化事件
    document.getElementById('statusFilter').addEventListener('change', function() {
        loadOrders();
    });

    document.getElementById('startDate').addEventListener('change', function() {
        loadOrders();
    });

    document.getElementById('endDate').addEventListener('change', function() {
        loadOrders();
    });

    // 绑定重置按钮事件
    document.getElementById('resetFilter').addEventListener('click', function() {
        document.getElementById('orderNoInput').value = '';
        document.getElementById('userIdInput').value = '';
        document.getElementById('statusFilter').value = '';
        document.getElementById('startDate').value = '';
        document.getElementById('endDate').value = '';
        loadOrders();
    });
});

// 加载订单统计数据
function loadOrderStats() {
    fetch('http://localhost:8080/api/admin/orders/statistics')
        .then(response => response.json())
        .then(data => {
            document.getElementById('todayOrders').textContent = data.todayOrders || 0;
            document.getElementById('todaySales').textContent = '¥' + (data.todaySales || 0).toFixed(2);
            document.getElementById('pendingShipment').textContent = data.pendingShipment || 0;
        })
        .catch(error => {
            console.error('Error loading order stats:', error);
        });
}

// 加载订单列表
function loadOrders(page = 1) {
    const orderNo = document.getElementById('orderNoInput').value;
    const userId = document.getElementById('userIdInput').value;
    const status = document.getElementById('statusFilter').value;
    const startDate = document.getElementById('startDate').value;
    const endDate = document.getElementById('endDate').value;

    let url = `http://localhost:8080/api/admin/orders?page=${page}&size=10`;
    if (orderNo) {
        url += `&orderNo=${encodeURIComponent(orderNo)}`;
    }
    if (userId) {
        url += `&userId=${encodeURIComponent(userId)}`;
    }

    if (status) {
        url += `&status=${status}`;
    }

    if (startDate) {
        url += `&startTime=${startDate}`;
    }

    if (endDate) {
        url += `&endTime=${endDate}`;
    }

    fetch(url)
        .then(response => response.json())
        .then(data => {
            renderOrders(data.items);
            renderPagination(data.page, data.totalPages);
        })
        .catch(error => {
            console.error('Error loading orders:', error);
            document.getElementById('orderTableBody').innerHTML =
                '<tr><td colspan="6" class="error">加载订单失败，请稍后重试</td></tr>';
        });
}

// 渲染订单列表
function renderOrders(orders) {
    const tbody = document.getElementById('orderTableBody');
    tbody.innerHTML = '';

    if (orders.length === 0) {
        tbody.innerHTML = '<tr><td colspan="6" class="no-data">暂无订单数据</td></tr>';
        return;
    }

    orders.forEach(order => {
        let statusText = '';
        switch(order.status) {
            case 0: statusText = '待支付'; break;
            case 1: statusText = '已支付'; break;
            case 2: statusText = '已发货'; break;
            case 3: statusText = '已完成'; break;
            case 4: statusText = '已取消'; break;
            default: statusText = '未知状态';
        }

        const row = document.createElement('tr');
        row.innerHTML = `
            <td><a href="admin-order-detail.html?orderId=${order.id}">${order.orderNo}</a></td>
            <td>${order.userId}</td>
            <td>¥${order.paymentAmount.toFixed(2)}</td>
            <td><span class="status-badge status-${order.status}">${statusText}</span></td>
            <td>${new Date(order.paymentTime).toLocaleString()}</td>
            <td>
                <a href="admin-order-detail.html?orderId=${order.id}" class="btn btn-sm btn-view">查看</a>
                ${order.status === 1 ? '<button class="btn btn-sm btn-ship" data-id="' + order.id + '">发货</button>' : ''}
                ${order.status < 2 ? '<button class="btn btn-sm btn-cancel" data-id="' + order.id + '">取消</button>' : ''}
            </td>
        `;
        tbody.appendChild(row);
    });

    // 绑定发货按钮事件
    document.querySelectorAll('.btn-ship').forEach(btn => {
        btn.addEventListener('click', function(e) {
            e.preventDefault();
            const orderId = this.getAttribute('data-id');
            window.location.href = `admin-order-detail.html?orderId=${orderId}&action=ship`;
        });
    });

    // 绑定取消按钮事件
    document.querySelectorAll('.btn-cancel').forEach(btn => {
        btn.addEventListener('click', function(e) {
            e.preventDefault();
            const orderId = this.getAttribute('data-id');
            if (confirm('确定要取消此订单吗？')) {
                cancelOrder(orderId);
            }
        });
    });
}

// 渲染分页控件
function renderPagination(currentPage, totalPages) {
    const pagination = document.getElementById('pagination');
    pagination.innerHTML = '';

    if (totalPages <= 1) return;

    // 上一页按钮
    if (currentPage > 1) {
        const prevLink = document.createElement('a');
        prevLink.href = '#';
        prevLink.className = 'page-link';
        prevLink.textContent = '上一页';
        prevLink.addEventListener('click', (e) => {
            e.preventDefault();
            loadOrders(currentPage - 1);
        });
        pagination.appendChild(prevLink);
    }

    // 页码按钮
    for (let i = 1; i <= totalPages; i++) {
        const pageLink = document.createElement('a');
        pageLink.href = '#';
        pageLink.className = 'page-link' + (i === currentPage ? ' active' : '');
        pageLink.textContent = i;
        pageLink.addEventListener('click', (e) => {
            e.preventDefault();
            loadOrders(i);
        });
        pagination.appendChild(pageLink);
    }

    // 下一页按钮
    if (currentPage < totalPages) {
        const nextLink = document.createElement('a');
        nextLink.href = '#';
        nextLink.className = 'page-link';
        nextLink.textContent = '下一页';
        nextLink.addEventListener('click', (e) => {
            e.preventDefault();
            loadOrders(currentPage + 1);
        });
        pagination.appendChild(nextLink);
    }
}

// 取消订单
function cancelOrder(orderId) {
    fetch(`http://localhost:8080/api/admin/orders/${orderId}/cancel`, {
        method: 'PUT'
    })
        .then(response => {
            if (response.ok) {
                alert('订单已取消');
                loadOrders();
            } else {
                alert('取消订单失败');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('操作失败，请重试');
        });
}